# -*- coding: utf-8 -*-
"""
---------------------------------------
@File    ：ip_call.py
@Author  ：liyunhui
@Date    ：2024/9/16 上午9:36 
@explain : 接口调用提供拨号云主机内网IP，指定拨号云主机重新拨号
---------------------------------------
"""
import json
import tornado
import traceback
from config import config
from methods.adsl_call import server_dial
from methods.custom_log import create_logging
from methods.redis_connect import get_redis_cli
from tornado_swagger.model import register_swagger_model


@register_swagger_model
class IpCallModel:
    pass


class IpCallHandler(tornado.web.RequestHandler):

    def __init__(self, *args, **kwargs):
        super(IpCallHandler, self).__init__(*args, **kwargs)
        self.logging = create_logging("ip_call")
        self.total_ip_key = config.ip_pool_total_ip
        self.redis_cli = get_redis_cli()

    def get(self):
        """
        拨号云主机重新拨号获取最新代理, GET 接收参数 intranet_ip
        ---
        tags:
        - IP 拨号
        summary: 根据内网 IP 获取云主机信息并重新拨号
        produces:
            - application/json
        parameters:
          - name: intranet_ip
            in: query
            description: 内网 IP
            required: true
            type: string
        responses:
          200:
            description: 成功获取云主机信息并执行拨号
            schema:
              type: object
              properties:
                status:
                  type: string
                  example: success
                message:
                  type: string
                server_info:
                  type: object
          400:
            description: 请求参数错误
            schema:
              type: object
              properties:
                status:
                  type: string
                  example: error
                message:
                  type: string
        """
        try:
            # 获取请求中的 intranet_ip 参数
            intranet_ip = self.get_argument("intranet_ip", None)
            if not intranet_ip:
                self.logging.error("缺少必要参数：拨号云主机内网IP")
                self.set_status(400)
                self.write(json.dumps({'status': 'error', 'message': 'intranet_ip 参数缺失'}))
                return

            # 根据内网 IP 获取云主机信息
            server_info = self.get_server_info(intranet_ip)
            if server_info:
                server_dial(
                    server_info=server_info,
                    intranet_ip=intranet_ip,
                    logging=self.logging
                )
                response = {
                    'status': 'success',
                    'message': '拨号任务已执行',
                    'server_info': server_info
                }
                self.set_header("Content-Type", "application/json")
                self.write(json.dumps(response))
            else:
                response = {
                    'status': 'failed',
                    'message': '未能获取到该云主机信息，无法执行拨号！',
                    'server_info': server_info
                }
                self.set_status(400)
                self.write(json.dumps(response))
                self.logging.error(f"拨号任务失败: {response}")

        except Exception as e:
            error_message = traceback.format_exc()
            self.set_status(400)
            self.write(json.dumps({'status': 'error', 'message': str(e)}))
            self.logging.error(f"拨号任务失败: {error_message}")

    def get_server_info(self, intranet_ip):
        """
        根据拨号服务器的内网IP获取该云主机的信息
        :param intranet_ip:
        :return:
        """
        try:
            server_info_key = self.total_ip_key + f":{intranet_ip}"
            server_data = self.redis_cli.hgetall(server_info_key)
            return server_data
        except:
            error_message = traceback.format_exc()
            self.logging.error(f"获取拨号云主机信息异常：{error_message}")
            return None
